package com.hlz.lib_wechat

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.os.Build
import android.util.Log
import com.hlz.lib_wechat.WeChatLogService
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.ListView
import android.widget.Toast

class WeChatLogService : AccessibilityService() {
    /**
     * 聊天对象
     */
    private var ChatName: String? = null

    /**
     * 聊天最新一条记录
     */
    private var ChatRecord = "test"
    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        Log.i(TAG, "onStartCommand: ")
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        val eventType = event.eventType
        Log.d(TAG, "onAccessibilityEvent: ")
        Log.d(TAG, "onAccessibilityEvent: ")
        Log.w(TAG, "onAccessibilityEvent: ")
        Log.i(TAG, "onAccessibilityEvent: $eventType")
        when (eventType) {
            AccessibilityEvent.TYPE_VIEW_SCROLLED -> {
                //获取当前聊天页面的根布局
                val rootNode = rootInActiveWindow
                //获取聊天信息
                getWeChatLog(rootNode)
            }
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED -> {
                //获取当前聊天页面的根布局
                val rootNode = rootInActiveWindow
                //获取聊天信息
                getWeChatList(rootNode)
            }
        }
    }

    private fun nodeClick(node : AccessibilityNodeInfo?){
        var clickNode = node;
        while (clickNode!=null){
            if(clickNode.isClickable){
                clickNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                break;
            }
//            clickNode = node?.parent
        }
    }

    private fun getWeChatList(rootNode: AccessibilityNodeInfo?) {
        rootNode?.let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                val list = it.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/fzg")
                if (!list.isNullOrEmpty()){
                    for (m in list){
                        val name = m.text.toString()
                        Log.i(TAG, "getWeChatList: "+name)
                        if (name.equals("a另一个自己")){
                            nodeClick(m)
                        }
                    }

                }
            } else {

            }
        }

    }


    /**
     * 遍历
     *
     * @param rootNode
     */
    private fun getWeChatLog(rootNode: AccessibilityNodeInfo?) {
        if (rootNode != null) {
            //获取所有聊天的线性布局

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {

                val  listChatRecord = rootNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/o")
                if (listChatRecord!!.size == 0) {
                    return
                }
                //获取最后一行聊天的线性布局（即是最新的那条消息）
                val finalNode = listChatRecord[listChatRecord.size - 1]

                //获取聊天对象list（其实只有size为1）
                val imageName = finalNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/i_")

                //获取聊天信息list（其实只有size为1）
                var record: List<AccessibilityNodeInfo>? = null
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    record = finalNode.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ib")
                }
                if (imageName!!.size != 0) {
                    if (record!!.size == 0) {
                        //判断当前这条消息是不是和上一条一样，防止重复
                        if (ChatRecord != "对方发的是图片或者表情") {
                            //获取聊天对象
                            ChatName = imageName[0].contentDescription.toString().replace("头像", "")
                            //获取聊天信息
                            ChatRecord = "对方发的是图片或者表情"
                            Log.i(TAG, "$ChatName：对方发的是图片或者表情")
                            Toast.makeText(this, "$ChatName：$ChatRecord", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        //判断当前这条消息是不是和上一条一样，防止重复
                        if (ChatRecord != record[0].text.toString()) {
                            //获取聊天对象
                            ChatName = imageName[0].contentDescription.toString().replace("头像", "")
                            //获取聊天信息
                            ChatRecord = record[0].text.toString()
                            Log.i(TAG, "$ChatName：$ChatRecord")
                            Toast.makeText(this, "$ChatName：$ChatRecord", Toast.LENGTH_SHORT).show()
                        }
                    }
                }

            }
        }
    }

    /**
     * 必须重写的方法：系统要中断此service返回的响应时会调用。在整个生命周期会被调用多次。
     */
    override fun onInterrupt() {
        Toast.makeText(this, "我快被终结了啊-----", Toast.LENGTH_SHORT).show()
    }

    /**
     * 服务开始连接
     */
    override fun onServiceConnected() {
        Toast.makeText(this, "服务已开启", Toast.LENGTH_SHORT).show()
        super.onServiceConnected()
    }

    /**
     * 服务断开
     *
     * @param intent 点击打开链接
     * @return
     */
    override fun onUnbind(intent: Intent): Boolean {
        Toast.makeText(this, "服务已被关闭", Toast.LENGTH_SHORT).show()
        return super.onUnbind(intent)
    }

    companion object {
        private const val TAG = "WeChatLogService"
    }
}